<?php
use com\gdl\common\dataobject\common\ResultDO; 
use com\gdl\kq\interfaces\AttAppOutgoServiceIf;
use com\gdl\kq\dataobject\outgo\OutgoDTO; 
use com\gdl\kq\dataobject\outgo\OutgoAllDTO;  
 
require(dirname(dirname(__FILE__)) ."/php_sdk-master/include.php");
use MagicCrypt\MagicCrypt;
/**
 * 考勤系统App外出相关 type=2
 */
class api_AttAppOutgoService extends api_Abstract implements AttAppOutgoServiceIf{
	
	# 默认留底照片
	static public $photo = "http://ot7pftuwd.bkt.clouddn.com/jgg8s6pc_264rfqm9vgty5ae187f645c25.jpg";
	
	//App外出申请
	public function addOutgo(OutgoDTO $outgo){ 
		#接受参数
		$userId = $outgo->userId ? gdl_lib_BaseUtils::getStr($outgo->userId) : "";
		$platformId = $outgo->platformId ? gdl_lib_BaseUtils::getStr($outgo->platformId) : "";
		$unitId = $outgo->unitId ? gdl_lib_BaseUtils::getStr($outgo->unitId) : "";
		$data = $outgo->data ? $outgo->data : ""; 
		
		# 实例化
		$result = new ResultDO();
        $result->success = true;
        $result->code = 400; 
        $result->data = [];
		#验证
		if(empty($data)){$result->message = "请求网络失败，请检查手机网络状态"; return $result;}
		$inserOutgoData = $data;
		try{
			# 外出申请记录表
			$outgoModel = new model_attendance_appoutgorecord();#外出记录表
			$leaveModel = new model_attendance_approvalprocessleaverecord();#请假表
			$processService = new service_appprocess();# 获取审批流程规则
			$gModel = new service_globals();
			$inserOutgoData['address'] = $gModel->format_html($inserOutgoData['address']);
			
			# s1 e1 s2 e2 || s1<=s2 e1>=s2
			$s = date("Y-m-d H:i",$inserOutgoData['startTime']);
			$end = date("Y-m-d H:i",$inserOutgoData['endTime']);
			#(startTime<{$inserOutgoData['startTime']} and endTime>{$inserOutgoData['startTime']})
			#验证 外出不能请假 请假不能外出 两个不能重复 补卡endTime<请假startTime
		
			//$emptyLeaveWhere = "((startTime>{$inserOutgoData['startTime']} && endTime>{$inserOutgoData['startTime']})  and (startTime <{$inserOutgoData['endTime']} and endTime>{$inserOutgoData['endTime']}) ) and memberId={$userId} and (status=1 or status=2)";
			$emptyLeaveWhere = "not ((endTime<{$inserOutgoData['startTime']} or startTime>{$inserOutgoData['endTime']})) and memberId={$userId} and (status=1 or status=2)";
			$emptyLeave = $leaveModel->selectOne($emptyLeaveWhere, 'id');
			
			if(!empty($emptyLeave)){$result->message = "您在{$s}到{$end}有一个重复请假"; return $result;}
			
			#重复的外出不能申请
			//$emptyOutgoWhere = "((startTime>{$inserOutgoData['startTime']} && endTime>{$inserOutgoData['startTime']})  and (startTime <{$inserOutgoData['endTime']} and endTime>{$inserOutgoData['endTime']}) ) and memberId={$userId} and (status=1 or status=2)";
			$emptyOutgoWhere = "not ((endTime<{$inserOutgoData['startTime']} or startTime>{$inserOutgoData['endTime']})) and memberId={$userId} and (status=1 or status=2)";
			$emptyOutgo = $outgoModel->selectOne($emptyOutgoWhere,'id');
			if(!empty($emptyOutgo)){$result->message = "您在{$s}到{$end}有一个重复外出申请"; return $result;}
			
			#查询审批流程
			$processResult = $processService->getMemberProcess($userId, $platformId, 2); #1:请假 2：外出 3：补卡 
			if(empty($processResult)){$result->message = "你还未加入考勤，请联系管理员添加"; return $result;}
			
			$inserOutgoData['proId'] = $processResult['id'] ? $processResult['id'] : 0; #审批流程id
			$inserOutgoData['proRule'] = $processResult['rules'] ? $processResult['rules'] : 0; #审批流程规则
			# 插入外出申请记录
			$ret = $outgoModel->insert($inserOutgoData);
			if($ret){
				#插入审批流程流程 申请id type  1：请假审批流程 2：外出审批流程 3：补卡审批流程
				$addApproval = $processService->insertApproval($userId, $processResult['rules'], $ret, 2);
				$result->message = "提交成功，等待审批"; 
				$result->code = 200;
				$result->data[] = [$ret];
			}else{
				$result->message = "网络环境异常，请检查手机网络状态";
			}
			
		}catch(Exception $ex){
			$result->message = $ex->getMessage();
		}
		 
        return $result; 
	}
	
    //App外出记录列表
	public function outgoList(OutgoAllDTO $outgo){
		#接受参数
		$userId = $outgo->userId ? gdl_lib_BaseUtils::getStr($outgo->userId) : "";
		$platformId = $outgo->platformId ? gdl_lib_BaseUtils::getStr($outgo->platformId) : "";
		$unitId = $outgo->unitId ? gdl_lib_BaseUtils::getStr($outgo->unitId) : "";
		$offset = $outgo->offset ? gdl_lib_BaseUtils::getStr($outgo->offset) : 1;
		$num = $outgo->num ? gdl_lib_BaseUtils::getStr($outgo->num) : 10;
		$data = $outgo->data ? gdl_lib_BaseUtils::getStr($outgo->data) : ""; 
		$likeTitle = $data['likeTitle']?$data['likeTitle']:"";
		$status = $data['status']?$data['status']:0;#状态 0：全部 1：审批完成 2：审批中 3：撤销
		
		# 实例化
		$result = new ResultDO();
        $result->success = true;
        $result->code = 400; 
        $result->data = [];
		#分页
		if($offset=='0') $offset=1;
		$limit = ($offset - 1) * $num . "," . $num;
		$group = 'order by id desc limit '.$limit;
		
		#条件查询
		$where = "memberId={$userId} ";
			if(!empty($likeTitle)){
				$where.=" and (numberId like '%".$likeTitle."%' or outGo like '%".$likeTitle."%') ";
			}
			if($status==1){
				$where.=" and (status=2 or status=3) ";
			}
			if($status==2){
				$where.=" and status=1 ";
			}
			if($status==3){
				$where.=" and status=4";
			}
		
		try{
			$outgoModel = new model_attendance_appoutgorecord();
			$filed = "id,numberId,memberId,FROM_UNIXTIME(startTime, '%Y.%m.%d %H:%i') as startTime, FROM_UNIXTIME(endTime, '%Y.%m.%d %H:%i') as endTime,numbers,outGo,address,lng,lat,radius,status,proMemberId,FROM_UNIXTIME(createTime, '%Y.%m.%d %H:%i') as createTime";
			$list = $outgoModel->select($where, $filed,$group)->items;
			
			if($list){
				# 遍历找审批人
				$list = $this->getMemberInfo($list, $userId);
				
				$listInfo['list'] = json_encode($list);
				$result->code = 200;
				$result->message = "获取成功";
				$result->data[]= $listInfo;
			}else{
				$result->code = 200;
				$result->message = "暂无数据";
			}
			
		}catch(Exception $ex){
			$result->message = $ex->getMessage();
		}
		 
        return $result;
	}
	
	//外出详情
	public function outgoInfo(OutgoDTO $outgo){
		$userId = $outgo->userId ? gdl_lib_BaseUtils::getStr($outgo->userId) : "";
		$platformId = $outgo->platformId ? gdl_lib_BaseUtils::getStr($outgo->platformId) : "";
		$unitId = $outgo->unitId ? gdl_lib_BaseUtils::getStr($outgo->unitId) : "";
		$data = $outgo->data ? gdl_lib_BaseUtils::getStr($outgo->data) : "";
		$recordId = $data['recordId'] ? $data['recordId']:"";
		$cardId = $data['cardId'] ? $data['cardId']:"";
		
		# 实例化
		$result = new ResultDO();
        $result->success = true;
        $result->code = 400; 
        $result->data = [];
		#验证
		if(empty($platformId)){$result->message = "请选择平台"; return $result;}
		if(empty($recordId)){$result->message = "请选择外出记录"; return $result;}
		
		try{
			$outgoModel = new model_attendance_appoutgorecord();
			$userModel = new model_attendance_member();
			
			$where = "id={$recordId}";
			$filed = "id,numberId,memberId,FROM_UNIXTIME(startTime, '%Y.%m.%d %H:%i') as startTime, FROM_UNIXTIME(endTime, '%Y.%m.%d %H:%i') as endTime,numbers,outGo,address,lng,lat,radius,status,proMemberId,FROM_UNIXTIME(createTime, '%Y.%m.%d %H:%i') as createTime,images";
			$info = $outgoModel->selectOne($where, $filed);
			if($info){
				#继续查用户
				$userWhere = "id={$info['memberId']}";
				$userFiled = "id,realName,photo,departmentId,unitId";
				$user = $userModel->selectOne($userWhere, $userFiled); #被审批用户
				$user['photo'] = $user['photo']?$user['photo']:self::$photo;
				$info['userInfo'] = $user; #被审批用户信息 
				$info['approvalUser'] = $this->getOneMember($recordId, $info['memberId']); #审批者信息
				
				$departmentId = $user['departmentId']?$user['departmentId']:$user['unitId'];
				$memberUserId = $user['id']?$user['id']:$info['memberId'];
				$memberUserInfo = $this->getMemberGroup($memberUserId,$departmentId,$platformId);
				$info['department'] = $memberUserInfo['department'];
				$info['agName'] = $memberUserInfo['agName'];
				$info['images'] = unserialize($info['images'])?unserialize($info['images']):[];
				$info['cardId'] = $cardId?$cardId:"";
				
				$recordIdInfo['data'] = json_encode($info);
				
				$result->message = "获取成功";
				$result->code = 200;
				$result->data[] = $recordIdInfo;
			}else{
				$result->message = "网络异常，请检查手机网络";
			}
		}catch(Exception $ex){
			$result->message = $ex->getMessage();
		}
		return $result;
	}
	
	//外出申请催办
	public function outgoUrge(OutgoDTO $outgo){
		#接受参数
		$userId = $outgo->userId ? gdl_lib_BaseUtils::getStr($outgo->userId) : "";
		$platformId = $outgo->platformId ? gdl_lib_BaseUtils::getStr($outgo->platformId) : "";
		$unitId = $outgo->unitId ? gdl_lib_BaseUtils::getStr($outgo->unitId) : "";
		$data = $outgo->data ? gdl_lib_BaseUtils::getStr($outgo->data) : "";
		$recordId = $data['recordId'] ? $data['recordId']:""; 
		
		# 实例化
		$result = new ResultDO();
        $result->success = true;
        $result->code = 400; 
        $result->data = [];
		
		try{
			$msgModel = new model_attendance_messagerecord();
			$outgoModel = new model_attendance_appoutgorecord();
			
			#找到审批人
			$approvalUser = $this->getOneMember($recordId, $userId);
			
			#催办时间间隔24小时只能催办一次
			$urgeWhere = "id={$recordId} and urge=1";
			$urge = $outgoModel->selectOne($urgeWhere, 'id,urgeTime,urge');
			$allow = 24*60*60; # 24消息
			if(!empty($urge)){
				$nowTime = time();
				$urgeTime = $urge['urgeTime'] ? intval($urge['urgeTime']) :0;
				$diff = $nowTime-$urgeTime;
				if($diff<$allow){
					$result->message = "一天只能催办一次";
					return $result;
				}
			}
			
			#插入消息
			if($approvalUser){
				
				#遍历下级审批人 # type=2 我的审批
				for($i=0; $i<count($approvalUser); $i++){
					$msgModel->insert(['type'=>2,'recordId'=>$recordId,'approvalId'=>$approvalUser[$i]['approvalId'],'userId'=>$approvalUser[$i]['id'],'msgInfo'=>'待我审批','createTime'=>time()]);
				}
				#发送成功修改催办时间
				$outgoModel->update("id={$recordId}",['urge'=>1,'urgeTime'=>time()]);
				
				$result->message = "催办提醒已发送";
				$result->code = 200; 
			}else{
				$result->message = "未找到相应审批人";
			}
		}catch(Exception $ex){
			$result->message = $ex->getMessage();
		}
		return $result;
	}
	
	//外出撤销
	public function outgoRevoke(OutgoDTO $outgo){
		#接受参数
		$userId = $outgo->userId ? gdl_lib_BaseUtils::getStr($outgo->userId) : "";
		$platformId = $outgo->platformId ? gdl_lib_BaseUtils::getStr($outgo->platformId) : "";
		$unitId = $outgo->unitId ? gdl_lib_BaseUtils::getStr($outgo->unitId) : "";
		$data = $outgo->data ? gdl_lib_BaseUtils::getStr($outgo->data) : "";
		$recordId = $data['recordId'] ? $data['recordId']:""; 
		
		# 实例化
		$result = new ResultDO();
        $result->success = true;
        $result->code = 400; 
        $result->data = [];
		
		try{
			$outgoModel = new model_attendance_appoutgorecord(); 
			$approvalModel = new model_attendance_approvalrecord();
			$msgModel = new model_attendance_messagerecord();
			
			#判断如果是已经通过的或撤销的则不再撤销
			$emptyWhere = "id={$recordId}";
			$emptyInfo = $outgoModel->selectOne($emptyWhere, "id,status");
			if($emptyInfo['status']==2 || $emptyInfo['status']==3 || $emptyInfo['status']==4){
				$result->message = "该申请已通过或撤销无法再次撤销";
				return $result;
			}
			
			#先改变外出表的状态为撤回 '审核状态：1：审批中 2：通过 3：不通过 4：用户撤回'
			$outgoWhere = "id={$recordId}";
			$outgoRet = $outgoModel->update($outgoWhere, ['status'=>4]);
			
			#再将要所有的审批层级为可见的审批改为撤回 审批类型：1：请假 2：外出 3：补卡 4：其他',
			$approvalWhere = "coverMemberId={$userId} and recordId={$recordId} and type=2";// and isShow=1
			$approvalRet = $approvalModel->update($approvalWhere, ['adopt'=>4]);
			
			#找审批人向他推送一条消息 告知已撤回
			$approvalUser = $this->getOneMember($recordId, $userId);
			if($approvalUser){
				for($i=0; $i<count($approvalUser); $i++){
					$msgModel->insert(['type'=>4,'recordId'=>$recordId,'approvalId'=>$approvalUser[$i]['approvalId'],'userId'=>$approvalUser[$i]['id'],'msgInfo'=>'待我审批的用户撤回','createTime'=>time()]);
				}
			}
			
			$result->message = "撤回成功";
			$result->code =200;
			
		}catch(Exception $ex){
			$result->message = $ex->getMessage();
		}
		
		return $result;
	}
	
	// atd_attendance_record 时间段 isGo =2 查询member=userID agId=当前考勤组 时间段
	//遍历找审批人 1:请假 2：外出 3：补卡
	private function getMemberInfo($list, $userId, $type=2){ 
		$outgoModel = new model_attendance_appoutgorecord(); 
		$userModel = new model_attendance_member();
		$leftJoin = [
			'atd_approve_record as r' => 'atd_app_outgo_record.id=r.recordId', 
		];
		$where = " r.id= (select MAX(rs.level) from atd_approve_record as rs where rs.isShow=1 and rs.type={$type}) and r.adopt=1 "; #可见并且最大审批层 and coverMemberId=zijiand MAX(r.level) r.isShow=1 and r.type=1 and 
		
		for($i=0; $i<count($list); $i++){
			#设置审批用户
			$list[$i]['approvalUser'] = [];
			#是否查询 如果审批通过不再查询数据库 状态为1为审批中才查询用户
			if($list[$i]['status']==1){
				#查找 审核状态为待审批3 被审批人为当前审批人 记录id为当前记录id 并且显示的审批分层id
				$where = " r.id= (select id from atd_approve_record as rs where rs.isShow=1 and rs.type={$type} and rs.adopt=1 and rs.coverMemberId={$userId} and rs.recordId={$list[$i]['id']} GROUP BY level DESC LIMIT 1) ";
				$recordInfo = $outgoModel->select($where, 'r.id,r.coverMemberId,r.memberId,r.adopt', '', '', $leftJoin)->items;
				if($recordInfo){
					for($j=0; $j<count($recordInfo); $j++){
						$userWhere = "id={$recordInfo[$j]['memberId']}";
						$userFiled = "id,realName";
						$userInfo = $userModel->selectOne($userWhere, $userFiled);
						$list[$i]['approvalUser'][] = $userInfo;
					}
				}
			}
		}
		
		return $list ? $list:[];
	}
	// 找审批人部门考勤组相关
	private function getMemberGroup($userId='', $departmentId='',$platformId=''){
		$info = ['department'=>'暂无部门', 'agName'=>'无考勤组'];
		if(empty($userId)){return false;}
		
		$unitsModel = new model_lhbase_units();
		$groupUserModel = new model_attendance_attendancegroupuser();
		$groupModel = new model_attendance_attendancegroup();
		#查被审批人的部门和考勤组
		$unitsWhere = "id={$departmentId}";
		$unitInfo = $unitsModel->selectOne($unitsWhere, 'id,unitName');
		$info['department'] = $unitInfo['unitName']?$unitInfo['unitName']:"暂无部门";
		
		#找该用户考勤组
		$memberWhere = "memberId={$userId} and type=1 and platformId={$platformId} "; #  and status=0 #目前做的物理删除该字段暂未用到 type1:参与考勤人员 2：无需参与考勤人员
		$memberGroup = $groupUserModel->selectOne($memberWhere, '*');
		$agId = $memberGroup['agId'] ? $memberGroup['agId'] : 0; #考勤组id
		#查找
		$agWhere = "id={$agId}";
		$agInfo = $groupModel->selectOne($agWhere, 'id,title');
		$info['agName'] = $agInfo['title'] ? $agInfo['title'] : "无考勤组";
		
		return $info;
	}
	
	//找单个审批人 外出申请id
	private function getOneMember($recordId,$userId, $type=2){
		
		$user = [];
		
		$outgoModel = new model_attendance_appoutgorecord(); 
		$userModel = new model_attendance_member();
		
		$leftJoin = [
			'atd_approve_record as r' => 'atd_app_outgo_record.id=r.recordId', 
		];
		$where = " r.id= (select MAX(rs.level) from atd_approve_record as rs where rs.isShow=1 and rs.type={$type}) and r.adopt=1 "; #可见并且最大审批层 and coverMemberId=zijiand MAX(r.level) r.isShow=1 and r.type=1 and 
		
		#查找 审核状态为待审批3 被审批人为当前审批人 记录id为当前记录id 并且显示的审批分层id
		$where = " r.id= (select id from atd_approve_record as rs where rs.isShow=1 and rs.type={$type} and rs.adopt=1 and rs.coverMemberId={$userId} and rs.recordId={$recordId} GROUP BY level DESC LIMIT 1) ";
		$recordInfo = $outgoModel->select($where, 'r.id,r.coverMemberId,r.memberId,r.adopt', '', '', $leftJoin)->items;
		if($recordInfo){
			for($j=0; $j<count($recordInfo); $j++){
				$userWhere = "id={$recordInfo[$j]['memberId']}";
				$userFiled = "id,realName";
				$userInfo = $userModel->selectOne($userWhere, $userFiled);
				$userInfo['approvalId'] = $recordInfo[$j]['id'];
				$user[] = $userInfo;
			}
		} 
		return $user;
	}
	
	
}

